import Taro from '@tarojs/taro'
import { SERVICE_URL_V1 } from "@/config/config"
import { getGlobalData, setGlobalData } from "@/utils/storage"
import { AUTH_TOKEN } from "@/config/storage"
import { toUserLoginPage } from "@/utils/page_router"

/**
 * 检查http状态值
 * @param res 响应数据
 * @returns {*}
 */
function checkHttpStatus(res: any) {
  // Taro.hideNavigationBarLoading()
  const { data, header } = res

  //  服务器时间
  data.timestamp = Number(new Date(header.Date))
  switch(res.statusCode) {
    case 200:
      return res.data
      break
    case 401:
      //  避免重复跳转登录
      if (res.isAuth && !getGlobalData('verifyLoginPage')) {
        setGlobalData({ verifyLoginPage: true })
        toUserLoginPage()
      }
      throwError(res)
      break
    default:
      const message = res.data.message
      Taro.hideLoading()
      Taro.showToast({ icon: 'none', title: message })
      // wx.showToast({ icon: 'none', title: message, mask: true })
      const error: any = new Error(message)
      error.data = res.data
      error.message = message
      error.code = res.statusCode
      throw error
  }
}

/**
 * 请求错误处理
 */
function throwError(err) {
  Taro.hideNavigationBarLoading()
  console.log(err)
  const error: any = new Error(err.data.message || '服务器走丢了!');
  error.code = err.code
  throw error
}

export default {
  request(options: any, method?: string) {
    const { url, isAuth=true } = options
    // Taro.showNavigationBarLoading()
    options.header = Object.assign({
      'Content-Type': 'application/json'
    }, options.header)

    // const token = getGlobalData('token')
    const token = Taro.getStorageSync(AUTH_TOKEN)
    if (token) {
      options.header = Object.assign(options.header,{
        'Access-Token': token
      })
    }

    return Taro.request({
      ...options,
      method: method || 'GET',
      url: /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/.test(url) ? `${url}` : `${SERVICE_URL_V1}${url}`,
    }).then(res => {
      return checkHttpStatus({ ...res, isAuth })
    }).catch(err => {
      console.log(err)
      throwError(err)
    })
  },
  get(options: any) {
    return this.request(options)
  },
  post(options: any) {
    return this.request(options, 'POST')
  },
  put(options: any) {
    return this.request(options, 'PUT')
  },
  del(options: any) {
    return this.request(options, 'DELETE')
  },
  upload(options: any) {
    // Taro.showNavigationBarLoading()
    const { url } = options
    options.header = Object.assign(options.header || {},{})

    const token = Taro.getStorageSync(AUTH_TOKEN)
    if (token) {
      options.header = Object.assign(options.header,{
        'Access-Token': token
      })
    }

    return new Promise((resolve, reject) => {
      Taro.uploadFile({
        ...options,
        url: /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/.test(url) ? `${url}` : `${SERVICE_URL_V1}${url}`,
        name: 'file',
        success (res){
          // Taro.hideNavigationBarLoading()
          const data:any = JSON.parse(res.data)
          resolve(data)
        },
        fail (err) {
          reject(err)
        }
      })
    })
  }
}
